﻿<script type="text/javascript" src="http://www.openlayers.org/api/OpenLayers.js"></script>
<script type="text/javascript" src="http://www.openstreetmap.org/openlayers/OpenStreetMap.js"></script>
<script type="text/javascript" src="http://myridetau.googlecode.com/svn/trunk/js/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="http://myridetau.googlecode.com/svn/trunk/js/jquery-plugins.js"></script>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">

var DEFAULT_PICTURE_URL = "http://myridetau.googlecode.com/svn/trunk/images/no_pic.gif";

var minimsg;
var IS_IE = window.attachEvent ? true : false;
var GEOCODING_ENABLED = true;
var tabs = new _IG_Tabs(__MODULE_ID__, "השבוע");
var prefs = new _IG_Prefs();
var serverUrl = prefs.getString("serverUrl");

var ROLE_NONE = 1;
var ROLE_HAS_CAR = 2;
var ROLE_NEED_RIDE = 3; 

var MORNING = 0;    
var EVENING = 1;


var week = [{ letter: 'א', dow: '1', name: 'ראשון', req_count: 0, thisWeek_req_count: 0, thisWeek_entries_count: 0  },            
			{ letter: 'ב', dow: '2', name: 'שני', req_count: 0, thisWeek_req_count: 0, thisWeek_entries_count: 0 },			
			{ letter: 'ג', dow: '3', name: 'שלישי', req_count: 0, thisWeek_req_count: 0, thisWeek_entries_count: 0 },			
			{ letter: 'ד', dow: '4', name: 'רביעי', req_count: 0, thisWeek_req_count: 0, thisWeek_entries_count: 0 },			
			{ letter: 'ה', dow: '5', name: 'חמישי', req_count: 0, thisWeek_req_count: 0, thisWeek_entries_count: 0 }];	
			
var CAR_OWNER_POSTIX = "נוסעים איתי";
var RIDE_SEARCHER_POSTFIX = "אני נוסע/ת עם";

var MAIL_HEADER = '<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><\/head><body style="direction: rtl">';
var MAIL_FOOTER = '<br><br>בתודה,<br>צוות myRide.<br><img src="http://myridetau.googlecode.com/svn/trunk/images/logo_small.gif"><\/body><\/html>';

var NEXT_WEEK = 1;
var PREV_WEEK = 2;
var SAME_WEEK = 3;

var thisWeekRows; 
var RequestsRows;
var scheduleRows;
var thisWeekDatesRows;
var WeekRequestsCountRow;
var currentUser;
var show_current_week = false;
var show_req_info = 0;
var currentWeekNum = -1; // this var can change according to the week shown in "this week" tab
var thisWeekNum = -1; // this var will hold the week num (1..53) of this week and will stay the same the whole run.

function formatDate(date) {
	if (!date) 
		date = new Date();

	return s = date.toJSON().replace(/[:\-TZ]+/g, "");	
}

function getDayPartPostfix(dow, dest_id) {
    var index = (dow - 1) * 2;

    if (parseInt(dest_id) == EVENING) 
        index = index + 1;
    
    var role = parseInt(scheduleRows[index].role);
    
    if (role == ROLE_HAS_CAR)
        return CAR_OWNER_POSTIX;
    
    if (role == ROLE_NEED_RIDE)
        return RIDE_SEARCHER_POSTFIX;
}

function getRole(dow, dest) {
    return scheduleRows[(dow - 1) * 2 + dest].role;
}
 
function translate() {
	
	// Note: by putting in an empty string for the source language ('es') then the translation
	// will auto-detect the source language.
	google.language.translate(MY_RIDE.displayName, 'en', 'he', function(result) {
    if (result.translation) {        
        var nameArray = result.translation.split(" ");
        $("#txtFirstName")[0].value = nameArray[0];
        $("#txtLastName")[0].value = nameArray[1];
    }
	
  });
}

// Creates all the tabs except for settings (which is always displayed)
function createTabs() {
	tabs.addTab("השבוע", "this_week");
	tabs.addTab("מי ייקח אותי", "who_take_me");
	tabs.addTab("מי נוסע איתי", "who_coming_with_me");	
}

function callServer(requests, callback, showMinimessage) {
	var loadMessage;
	if (showMinimessage === undefined || showMinimessage == true) {
		loadMessage = minimsg.createStaticMessage("אנא המתן...");
	}
	
	var url = serverUrl + "nocache=" + new Date().getTime();	              

	var jsonData = gadgets.json.stringify(requests);
    jsonData = $.base64Encode(jsonData); 
    
    var params = {};
    params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.POST;
   	params[gadgets.io.RequestParameters.POST_DATA]= jsonData;
    params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.JSON;
	params[gadgets.io.RequestParameters.REFRESH_INTERVAL] = 10;
    
    gadgets.io.makeRequest(url, function(response) {
		if ( !(loadMessage === undefined) ) {
			minimsg.dismissMessage(loadMessage);
		}		
	
        if (response.rc == "200") {
            callback(response);
        }
        else {
            minimsg.createTimerMessage("שגיאת שרת. אנא נסו שוב", 3);
        }
    }, params);    
}

function allResponsesSuccessful(responses) {
	for (i in responses) {
		if (responses[i].status != "success") {
			alert("Response number " + i + " failed.");
			return false;	
		}
	}
	
	return true;
}
	
function generateRequest(car_owner_id, dest, dow, email, time, row_idx) {		
	
	var Myparams = {};
			
	Myparams["db_seeker"]  = MY_RIDE.uid; 
	Myparams["db_carOwner"] = car_owner_id; // check why  car_owner_id returned with error 
	Myparams["db_dest"] = dest;
	Myparams["db_day"] = dow;
	Myparams["db_text"] = document.getElementById(car_owner_id).value; 

	if (Myparams.db_text == "") Myparams.db_text = " ";
	
	mailText = MAIL_HEADER + currentUser.first_name + ' רוצה לנסוע איתך ביום ' + week[dow-1].letter + '\' בשעה ' + time + '.<br>הודעה מ' + currentUser.first_name + ': ' + Myparams["db_text"] + "<br>" + MAIL_FOOTER;
	           	
	var requests = [{ 
					   op: 'DB', 
					   sp: 'sp_AddRequest',
					   params: Myparams
				    },
				    {
				        op: 'SENDMAIL', 
					    to: email,
					    subject: 'התקבלה בקשה מ myRide',
					    message: mailText
					}];                       
    /*alert("details "+ requests[requests.length-1]['params']['db_carOwner'] +" " +
			requests[requests.length-1]['params']['db_dest'] + " " +
			requests[requests.length-1]['params']['db_day'] ); //+ " " + requests[0][params].db_reqid);
    */
	callServer(requests, function(response) {
	    refreshThisWeek(SAME_WEEK);
	    $("#item_who_take_me_" + car_owner_id + "_" + row_idx).remove(); 
	    minimsg.createTimerMessage("הבקשה נשלחה", 3);
	} );
}

function saveUserDetails() {		
	var streetInfo = { 
		city_name: $("#txtCity")[0].value,
		street_name: $("#txtStreet")[0].value
	};
	var coordsUrl = "http://www.freemap.co.il/libs/lookup.php?" + gadgets.io.encodeValues(streetInfo);
	
	if (GEOCODING_ENABLED) {
		var loadMessage = minimsg.createStaticMessage("אנא המתן...");
	    var requestParams = {};
	    requestParams[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.GET;

	    gadgets.io.makeRequest(coordsUrl, function(response) {
			minimsg.dismissMessage(loadMessage);
		    if (response.errors.length != 0) {
			    minimsg.createTimerMessage("שגיאה בגישה לשרת כתובות. אנא נסה שוב", 3);
			    return;
		    }
		    eval("var data = " + response.text + ";");
		    if (data.reply.found == 0) {
			    minimsg.createTimerMessage("הכתובת שניתנה לא נמצאה. אנא בחר כתובת אחרת", 3);
			    return;
		    }
		    var coords = data.reply.point.split(" ");
		    saveDetailsWithCoords(coords[0], coords[1]);
	    }, requestParams);
	}
	else {
	    saveDetailsWithCoords(currentUser.lag, currentUser.lat);
	}
}

function saveDetailsWithCoords(lon, lat) {
	var params = {
		db_user_id:	MY_RIDE.uid,
		db_first_name: $("#txtFirstName")[0].value,
		db_last_name: $("#txtLastName")[0].value,
		db_city: $("#txtCity")[0].value,
		db_street: $("#txtStreet")[0].value,
		db_house_num: $("#txtHouseNum")[0].value,				
		db_faculty: $("#txtFaculty")[0].value,
		db_hobbies: $("#txtHobbies")[0].value,
		db_participation: $("#txtParticipation")[0].value,
		db_lon: lon,
		db_lat: lat,
		db_image_url: $("#txtImageUrl")[0].value != "" ? $("#txtImageUrl")[0].value : DEFAULT_PICTURE_URL,
		db_email: $("#txtEmail")[0].value		
	};
		
	var requests = [{ 
		   op: 'DB', 
		   sp: 'sp_UpdateUser',
		   params: params
	}];			   

    callServer(requests, function(response) {    	
    	if (!response.data) {
			minimsg.createTimerMessage("שגיאה בזמן שמירת הנתונים", 3);
			return;	
		}

    	minimsg.createTimerMessage("השינויים נשמרו בהצלחה", 3);

    	// Reload everything
    	if (MY_RIDE.isNewUser) {
    	    $("#personal_details").click();
    		$("#schedule_details").click();
    	}
    });
}

function validateUserSchedule() {
	var timeRegex = /^\s*(\d{1,2}):(\d{2})\s*$/;
	
	for (var day=1; day<=5; ++day) {
		for (var dest=0; dest<=1; ++dest) {
			var dayDestId = day + "-" + dest;
			var timeText = document.getElementById("txtSched" + dayDestId);
			var roleSelect = document.getElementById("selSched" + dayDestId);
			var role = roleSelect.options[roleSelect.selectedIndex].value;
			var time = timeText.value;
			var matches = timeRegex.exec(time);
			
			if (role != ROLE_NONE) {
				if (matches == null ||
					matches[1] < 0 || matches[1] > 23 ||
					matches[2] < 0 || matches[2] > 59) {				
					timeText.focus();
					timeText.select();
					return false;
				}
			}
		}
	}
	return true;			
}

function saveUserSchedule() {	
	var requests = [ ];
	
	if (!validateUserSchedule()) {
		minimsg.createTimerMessage("יש להקיש שעה תקנית HH:MM", 3);
		return;
	}

    for (var day=1; day<=5; ++day) {
        for (var dest=0; dest<=1; ++dest) {
            var dayDestId = day + "-" + dest;
            var roleSelect = document.getElementById("selSched" + dayDestId); 
            var role = roleSelect.options[roleSelect.selectedIndex].value;
            var time = document.getElementById("txtSched" + dayDestId).value;                
            
            var params = {};
            params["db_uid"]  = MY_RIDE.uid; ;
            params["db_day"]  = day;
            params["db_dest"] = dest;
            params["db_role"] = role;
            params["db_time"] = time;
			
			if (params["db_role"] == ROLE_NONE) {
				params["db_time"] = "";
			}
            
            requests[requests.length] = { 
            				   op: 'DB', 
            				   sp: 'sp_SetUserSchedule',
            				   params: params           
            				};             
        }
    }
    
    requests[requests.length] = {
					                op: 'DB',
					                sp: 'sp_GetUserSchedule',
					                params: { db_uid: MY_RIDE.uid }   
				                };
    
    callServer(requests, function(response) {    	
    	if (!response.data) {
			minimsg.createTimerMessage("שגיאה בזמן שמירת הנתונים", 3);
			return;	
		}
        scheduleRows = response.data[response.data.length-1].rows;		
		minimsg.createTimerMessage("השינויים נשמרו בהצלחה", 3);
		
		// Registration is done, reload the gadget so the user can start using it.
    	if (MY_RIDE.isNewUser) {    	    
            document.location.reload();
        } else {
    	    refreshThisWeek(SAME_WEEK);
    	}
    });		
}

function selectByValue(select, value) {
	for (var i = 0; i < select.options.length; i++ ) {
		if (select.options[i].value == value) {
			select.selectedIndex = i;
			return;
		}
	}
}

function updateScheduleForm(obj) {
    var response = obj;
    if (response.status == "failure") {
        // TODO deal with it
        alert("Error occurred!");
        return;
    }
    
    for (var row in response.rows) {
        var day  = response.rows[row].day_of_week;
        var dest = response.rows[row].destination;
        var role = response.rows[row].role;
        
        var time;
        if (response.rows[row].formatted_time === undefined) {
            time = "";
        }
        else {
            time = response.rows[row].formatted_time;
        }
        
        var dayDestId = day + "-" + dest;
        selectByValue(document.getElementById("selSched" + dayDestId), role);
        document.getElementById("txtSched" + dayDestId).value = time;
    }
}

function initSearchDialog() {				
	var currentTime = new Date();
	var loopEnd = currentTime.getDay(); 
	
	// in case today is Saturday we dont want to have an array overflow.
	if (loopEnd == 6)
		loopEnd = loopEnd - 1;
	
	var options = [	{ text: 'ראשון', value: '1' },            
					{ text: 'שני', 	 value: '2' },			
					{ text: 'שלישי', value: '3' },			
					{ text: 'רביעי', value: '4' },			
					{ text: 'חמישי', value: '5' }];	
	
	for(i=0; i < loopEnd; i++)
		options[i].text = options[i].text + " (הבא)";
		
	$('select.day-select').each(function() {
		addOptionsToSelect(this, options);	
	});				
}

function setStreetAcSettings(cityName) {
	var streetAcParams = {};
	streetAcParams["extraParams"] = { name: "street_name", city_name: encodeURI(cityName) };
	streetAcParams["maxItemsToShow"] = 5;
	streetAcParams["minChars"] = 2;
	// streetAcParams["mustMatch"] = 1;

	$("#txtStreet").autocomplete("http://www.freemap.co.il/libs/jcomplete.php", streetAcParams);
}

function initSettingsDialog(response) {		
	if (response.status != 'success') 
		alert("initSettingsDialog: Error");
		 
	var options = response.rows;			
		
	$('select.role-select').each(function() {
		addOptionsToSelect(this, options);	
	});			

	var params = {};
	params["extraParams"] = { name: "city_name" };
	params["maxItemsToShow"] = 5;
	params["minChars"] = 2;
	// params["mustMatch"] = 1;
	params["onItemSelect"] = function(li) {
		// $("#txtStreet")[0].value = "";
		setStreetAcSettings(li.innerText);
	};

	$("#txtCity").autocomplete("http://www.freemap.co.il/libs/jcomplete.php", params);
	setStreetAcSettings($("#txtCity")[0].value);
}

function refreshThisWeek(flag) {
	if (flag == NEXT_WEEK) currentWeekNum++;
	if (flag == PREV_WEEK) currentWeekNum--;
	if (currentWeekNum == 54) currentWeekNum = 1;
	if (currentWeekNum == 0) currentWeekNum = 53;
	
     requests = [{
					op: 'DB',
					sp: 'sp_GetThisWeek',
					params: { db_uid: MY_RIDE.uid, db_week_num: currentWeekNum } 
				},
				{
					op: 'DB',
					sp: 'sp_GetCurrentWeekDates',
					params: { db_week_num: currentWeekNum }
				}, 
				{
					op: 'DB',
					sp: 'sp_GetCountOfWaitingRequests',
					params: { db_uid: MY_RIDE.uid, db_week_num: currentWeekNum}
				},
				{
					op: 'DB',
					sp: 'sp_GetRequests',
					params: { db_uid: MY_RIDE.uid }
				}
				];								
				
	$('#this_week').addClass('loading_big');
													
	callServer(requests, function(response) {
		$('#this_week').removeClass('loading_big');
		if (!allResponsesSuccessful(response.data)) return;
		thisWeekRows = response.data[0].rows;
		thisWeekDatesRows = response.data[1].rows;	 		
		WeekRequestsCountRow = response.data[2].rows[0];
		RequestsRows = response.data[3].rows;	 				
		week[0].req_count = WeekRequestsCountRow.sunday_count;
		week[1].req_count = WeekRequestsCountRow.monday_count;
		week[2].req_count = WeekRequestsCountRow.tuesday_count;
		week[3].req_count = WeekRequestsCountRow.wednesday_count;
		week[4].req_count = WeekRequestsCountRow.thursday_count;
		
		for (i=0; i<5; i++) {
			week[i].thisWeek_entries_count = 0;
			for (j in thisWeekRows) {
				if (thisWeekRows[j].day_of_week == (i+1))
					week[i].thisWeek_entries_count++;
			}
		}
			
		$('#this_week').children('.list_item').remove();
		$('#this_week').children('.this_week_item').remove();
		$('#this_week').children('.req_info_item').remove();
		
        renderRows("this_week", week, null, { state: 'this_week' });  // oded
        refreshWhosComingWithMe();
        
    }, false);        
}

function renderThisWeekDay(data, context) {
    var morning = "<div class='day_part'>לאוניברסיטה " + getDayPartPostfix(data.dow, MORNING) + ":<\/div>";
	var evening = "<div class='day_part'>מהאוניברסיטה " + getDayPartPostfix(data.dow, EVENING) + ":<\/div>";
	//var searchBtn = "אין טרמפים ברשימה כרגע<br><input type='button' value='חפש טרמפים'>";
	var searchBtn = "אין טרמפים ברשימה כרגע";
	var noRidesMsg = "אין טרמפים ברשימה כרגע";
	var morningHasRides = false;
	var eveningHasRides = false;
	
	// If the role is none, we don't want to show anything
	if (getRole(data.dow, MORNING) == ROLE_NONE) morning = "";
	if (getRole(data.dow, EVENING) == ROLE_NONE) evening = "";
	
	for (i in thisWeekRows) {
		var row = thisWeekRows[i];

		// Skip rows that don't match the current day being rendered
		if (row.day_of_week != data.dow) 
			continue;


        // If the current user is the car owner, the passenger id is the other party,
        // if not, it's the current user
        if (row.car_owner == currentUser.user_id) {
		    context.passenger_id = row.user_id
		}
		else {
		    context.passenger_id = currentUser.user_id
		}
		
		if (row.dest_id == "0") { 
			morning += renderTemplate("#user_list_item", row, context);
			morningHasRides = true;
		}
		else {
			evening += renderTemplate("#user_list_item", row, context);
			eveningHasRides = true;
		}		
	}

	if (!morningHasRides && getRole(data.dow, MORNING) == ROLE_NEED_RIDE)
		morning += searchBtn;

	if (!eveningHasRides && getRole(data.dow, EVENING) == ROLE_NEED_RIDE)
		evening += searchBtn;

	if (!morningHasRides && getRole(data.dow, MORNING) == ROLE_HAS_CAR)
		morning += noRidesMsg;

	if (!eveningHasRides && getRole(data.dow, EVENING) == ROLE_HAS_CAR)
		evening += noRidesMsg;

    if (morning + evening == "")
	    return "אין נסיעות ביום זה.";
	else {
	    //alert(morning + evening);
	    return morning + evening;
	}
}

function renderCurrentWeek(data, context) {
	if (show_current_week == false)
		return "";	
	
	show_current_week = false;
	show_req_info = 0;
	var html;
	var row = thisWeekDatesRows[0];
	
	// for the first time only we keep the week number (1-53) from here on we will update currentWeekNum according to the current week the user views at "this week" tab
	// while  thisWeekNum will stays the same
	if (currentWeekNum == -1) {
		thisWeekNum = currentWeekNum = row.week_num;		
	}
		
	html = renderTemplate("#show_current_week", row, context);
	return html;
}


function renderWhosCommingWithMe(data, context) {
    //var day = "<div class='day_part'>סטטוס בקשות ליום זה:<\/div>";
	var day = "";
	var noReqForToday = "לא נמצאו בקשות ליום זה";
	var dayHasReqs = false;
	
	
	for (i in RequestsRows) {
		var row = RequestsRows[i];
		row.row_idx = i;

		// Skip rows that don't match the current day being rendered
		if (row.day_of_week != data.dow) 
			continue;	
		
		day += renderTemplate("#user_list_item", row, context);
		dayHasReqs = true;				
	}

	if (!dayHasReqs) // && scheduleRows[(data.dow - 1) * 2].role == ROLE_HAS_CAR )
		day += noReqForToday;
	
	return day; 
} 

function refreshWhosComingWithMe() {	
	$('#who_coming_with_me').children('.list_item').remove();
	renderRows("who_coming_with_me", week, null, { state: 'who_coming_with_me' });	
}

function updateDetailsDialog(response) { 
    document.getElementById('txtFirstName').value = currentUser.first_name;
    document.getElementById('txtLastName').value = currentUser.last_name;
    document.getElementById('txtCity').value = currentUser.city;
    document.getElementById('txtStreet').value = currentUser.street;
    document.getElementById('txtHouseNum').value = currentUser.house_num;
    document.getElementById('txtFaculty').value = currentUser.faculty;
    document.getElementById('txtHobbies').value = currentUser.hobbies;
    document.getElementById('txtParticipation').value = currentUser.participation;
    document.getElementById('txtImageUrl').value = currentUser.image_url;    
    document.getElementById('txtEmail').value = currentUser.email;            
}
google.load("language", "1"); 
function getUID() {
	
    var params = {};
    params[opensocial.DataRequest.PeopleRequestFields.PROFILE_DETAILS] = [opensocial.Person.Field.INTERESTS, opensocial.Person.Field.ACTIVITIES, opensocial.Person.Field.PROFILE_URL];    
    
    var req = opensocial.newDataRequest();
    req.add(req.newFetchPersonRequest(opensocial.IdSpec.PersonId.OWNER, params), "viewer");    
    req.send(function(data) {
        var viewer = data.get('viewer');
        if (viewer.getErrorCode() == "forbidden") {
            $("body").html("<br><br><center>יש לאפשר גישה לפרופיל ב OpenSocial ולבצע רענון של הדף.<br><br><img src='http://myridetau.googlecode.com/svn/trunk/images/logo_small.gif'><\/center>");
            return;
        }
        
        if (viewer.hadError()) {
            alert("OpenSocial Error (" + viewer.getErrorCode() + "): " + viewer.getErrorMessage());
            return;
        }
        viewerData = viewer.getData();
        var nameArray = viewerData.getDisplayName().split(" ");
        
        MY_RIDE = { 
                    opensocial_id: viewerData.getId(),
                    imageUrl: viewerData.getField(opensocial.Person.Field.THUMBNAIL_URL),
                    displayName: viewerData.getDisplayName(),
                    firstName: nameArray[0],
                    lastName: nameArray[1]
                    /*interests: viewerData.getField(opensocial.Person.Field.INTERESTS),
                    activities: viewerData.getField(opensocial.Person.Field.ACTIVITIES),
                    profileUrl: viewerData.getField(opensocial.Person.Field.PROFILE_URL)*/
                };


        //MY_RIDE.opensocial_id = '109999908224705846665'; // TODO: DELETE!!!        
        //MY_RIDE.opensocial_id = '103620583417053285958'; // TODO: DELETE!!!   
        //MY_RIDE.displayName = "Hofit Biran" ;
		//$('body').append('<img src="' + MY_RIDE.imageUrl + '">');                 
        //$("#who_take_me").append(MY_RIDE.uid);
        //alert("DEBUG: your google ID is " + MY_RIDE.uid);               
        
        requests = [{
						op: 'DB',
						sp: 'sp_GetUserByOpensocialId',
						params: { db_opensocial_id: MY_RIDE.opensocial_id }  
					}];

			
        callServer(requests, function(response) {		
        	if (!response.data) {
    			alert("שגיאה בזמן log-in");
    			return;	
    		}						
        	currentUser = response.data[0].rows[0];        	        	                                
        	MY_RIDE["uid"] = currentUser.user_id;
        	MY_RIDE["isNewUser"] = currentUser.first_name == '';
            
        	if (!MY_RIDE.isNewUser) {
        	    $("#new_user_msg").remove();        	    
        	    createTabs();        	    
        	}
        	else {
        	    $("#search_bar").html("");	        	    
        	    translate();
        	}
			
        	tabs.addTab("הגדרות", "settings");
        	if (MY_RIDE.isNewUser) {
        	    tabs.setSelectedTab(0);        	    
        	}

        	$("div").removeClass("hidden");
        	
        	postInit();    		
    	}, false);		
    	                
    });
}

function init() {	
	
    minimsg = new gadgets.MiniMessage(__MODULE_ID__, document.getElementById("minimsg_div"));
	
	// Bypass google caching of URL sources
    $('*[srcNoCache]').attr('src', function() {
        var src = this.getAttribute('srcNoCache');
        this.removeAttribute('srcNoCache');
        return src;
    });
    
     if (IS_IE) {
        document.styleSheets[0].addRule(".plus", "float: none !important", 0);
        //alert(document.styleSheets[0]);
    }


	getUID();	
}

function postInit() {
    requests = [{ 
					op: 'DB', 
					sp: 'sp_GetRoles', 
					params: { } 
				},
				{
					op: 'DB',
					sp: 'sp_GetUserSchedule',
					params: { db_uid: MY_RIDE.uid }   
				},								
				{
					op: 'DB',
					sp: 'sp_GetThisWeek',
					params: { db_uid: MY_RIDE.uid, db_week_num: currentWeekNum } 
				},
				{
					op: 'DB',
					sp: 'sp_GetRequests',
					params: { db_uid: MY_RIDE.uid }
				},
				{
					op: 'DB',
					sp: 'sp_GetCurrentWeekDates',
					params: { db_week_num: currentWeekNum }
				},
				{
					op: 'DB',
					sp: 'sp_GetCountOfWaitingRequests',
					params: { db_uid: MY_RIDE.uid, db_week_num: currentWeekNum}
				}				
				];					
				
		
		
	callServer(requests, function(response) {
		if (!response.data) {
			alert("שגיאת תקשורת");
			return;	
		}
		
		if (!allResponsesSuccessful(response.data)) return;

		scheduleRows = response.data[1].rows;		
		thisWeekRows = response.data[2].rows;
		RequestsRows = response.data[3].rows;	 			
		thisWeekDatesRows = response.data[4].rows;	 			
		WeekRequestsCountRow = response.data[5].rows[0];	 			
		
		initSettingsDialog(response.data[0]);		
					
		week[0].thisWeek_req_count = week[0].req_count = WeekRequestsCountRow.sunday_count;
		week[1].thisWeek_req_count = week[1].req_count = WeekRequestsCountRow.monday_count;
		week[2].thisWeek_req_count = week[2].req_count = WeekRequestsCountRow.tuesday_count;
		week[3].thisWeek_req_count = week[3].req_count = WeekRequestsCountRow.wednesday_count;
		week[4].thisWeek_req_count = week[4].req_count = WeekRequestsCountRow.thursday_count;
			

			
		for (i=0; i<5; i++) {
			week[i].thisWeek_entries_count = 0;
			for (j in thisWeekRows) {
				if (thisWeekRows[j].day_of_week == (i+1))
					week[i].thisWeek_entries_count++;
			}	
		}
		
		if (!MY_RIDE.isNewUser) {
			initSearchDialog();
			updateDetailsDialog();			
			updateScheduleForm(response.data[1]);				
			
			renderRows("this_week", week, null, { state: 'this_week' }); //oded 
			renderRows("who_coming_with_me", week, null, { state: 'who_coming_with_me' });
		}
		else 
		{		    
            pic = MY_RIDE.imageUrl;
            if (!pic === undefined && pic.indexOf("public") > -1)
                document.getElementById('txtImageUrl').value = pic;       
		}
						
		// Click handlers for plus / minus
		$('.plus').live("click", function() {
			$(this.parentNode).children().filter(".details").toggle("fast");		
			$(this).toggleClass("minus");
			$(this.parentNode).toggleClass("sel");		
		});

		if (MY_RIDE.isNewUser) {
		    $("#personal_details").click();
		}						
	}, false);		
}

// Call init function to initialize and display tabs.
_IG_RegisterOnloadHandler(init);

function addOptionsToSelect(select, options) {
	for (i in options) {
		var optNode = document.createElement('option');		
		optNode.text = options[i].text;
		optNode.value = options[i].value;
		
		if (IS_IE)		
			select.add(optNode);
		else
			select.add(optNode, null);
	}
}

function renderTemplate(template, data, context) {		
	var templateCallRegExp = /{\$([a-zA-Z0-9#\-_]+)}/;
	var functionCallRegExp = /{@([a-zA-Z0-9\-_]+)}/;
	var matches;
	var html = $(template + ".template").html();		
	
	if (html == null) {
		alert("Error: Template '"  + templateId + "' not found. did you forget the 'template' class?");
	}
      
    html = html.replace(/%7B/g, '{');
    html = html.replace(/%7D/g, '}');

	// Render the data fields
	for (var field in data) {				
		var re = new RegExp('{:' + field + '}', 'g');
		
		html = html.replace(re, data[field]);
    }
	
	// Render context fields
	for (var field in context) {				
		var re = new RegExp('{:' + field + '}', 'g');
		
		html = html.replace(re, context[field]);  				
	}
	 
	// Call sub templates
	while ((matches = templateCallRegExp.exec(html)) != null) {		
		var callArray = matches[1].split("#");
		var templateId;
		var render = true;
		
		// Look for a state condition
		if (callArray.length > 1) {
			templateId = callArray[1];
			
			// Check if the current state matches the prefix
			render = (context && context.state == callArray[0]); 
		}
		else 
			templateId = callArray[0];						
		
		if (render)
			html = html.replace(matches[0], renderTemplate("#" + templateId, data, context));
		else {
			html = html.replace(matches[0], "");				
		}
	}
	
	// Call functions
	while ((matches = functionCallRegExp.exec(html)) != null) {
		var functionName = matches[1];
		
		html = html.replace(matches[0], eval(functionName + "(data, context)"));						
	}
	
	return html;
}

function renderRows(containerId, rows, filter, context) { 					
	if (containerId == "this_week") {
		show_current_week = true;
		show_req_info = 0;	
	}
	
	for (i in rows) {
		var data = rows[i];		
		data.row_idx = i;
				
		// apply filter if applicable
		if (filter && !filter(data, context)) 
			continue;
		
		var html = renderTemplate('#' + containerId + ' div', data, context);				
						
		$('#' + containerId).append(html);							
	}		
}

function showMap(containerId, lag, lat) {
	$('#' + containerId).toggle("fast", function() {
        if (this.innerHTML != "") { 
            this.map.updateSize();
            return;
        }

        // Create a new map
        this.map = new OpenLayers.Map(containerId, {
            controls: [new OpenLayers.Control.PanZoomBar()],
            units: 'm',
            projection: new OpenLayers.Projection("EPSG:900913"),
            displayProjection: new OpenLayers.Projection("EPSG:4326")
        });

        // Add open street map layer
        this.map.addLayer(new OpenLayers.Layer.OSM.Osmarender("Osmarender"));
        
        // Calculate the coordinate
        var lonLat = new OpenLayers.LonLat(lag, lat).transform(
            new OpenLayers.Projection("EPSG:4326"), this.map.getProjectionObject());
        
        // Add the markers
        var markers = new OpenLayers.Layer.Markers("Markers");
        var size = new OpenLayers.Size(25,25);
        var offset = new OpenLayers.Pixel(-(size.w/2), -size.h);
        var icon = new OpenLayers.Icon('http://myridetau.googlecode.com/svn/trunk/images/red_marker.png',size,offset);
        markers.addMarker(new OpenLayers.Marker(lonLat,icon));
        this.map.addLayer(markers);
        
        this.map.setCenter(lonLat, 16);
        this.map.zoomOut();
    });
}

function searchRides() {
	var daySelect = document.getElementById("selDay"); 
    var dayVal = daySelect.options[daySelect.selectedIndex].value;	
			
	newRequests = [{
					op: 'SEARCH',					
					params: { db_uid: MY_RIDE.uid, db_day: dayVal }
				  }];
					
	callServer(newRequests, function(response) {
	    if (!allResponsesSuccessful(response.data)) return;
		
        var data = response.data[0].rows;
        var noResults = '<div class="list_item">לא נמצאו טרמפים<\/div>';
        
        // Remove old items
        $('#who_take_me div.list_item').remove();
        
        // Add new items or a "no results" message
        if (data.length == 0)
            $('#who_take_me div').append(noResults);
	    else
	        renderRows("who_take_me", data, null, { state: 'who_take_me' });		
	});
}

function ApproveRequest(ride_id, passenger_id, email, date, time) {
	//alert("ride id = " + ride_id + " passanger_id = " + passenger_id);
	
	mailText = MAIL_HEADER + currentUser.first_name + ' אישר/ה את בקשתך לטרמפ בתאריך ' + date + ' בשעה ' + time + '.<br>' + MAIL_FOOTER;	           				
	newRequests = [{
					    op: 'DB',
					    sp: 'sp_ApproveRequest',
					    params: { db_ride_id: ride_id, db_passenger_id: passenger_id }
					},
					{
				        op: 'SENDMAIL', 
					    to: email,
					    subject: 'בקשתך לטרמפ אושרה',
					    message: mailText
					},
					{
					op: 'DB',
					sp: 'sp_GetRequests',
					params: { db_uid: MY_RIDE.uid }
					},
					{
					op: 'DB',
					sp: 'sp_GetCountOfWaitingRequests',
					params: { db_uid: MY_RIDE.uid, db_week_num: currentWeekNum}
					}];
					
	callServer(newRequests, function(response) {
		if (!allResponsesSuccessful(response.data)) return;
		
		RequestsRows = response.data[2].rows;
		WeekRequestsCountRow = response.data[3].rows[0];
		week[0].req_count = WeekRequestsCountRow.sunday_count;
		week[1].req_count = WeekRequestsCountRow.monday_count;
		week[2].req_count = WeekRequestsCountRow.tuesday_count;
		week[3].req_count = WeekRequestsCountRow.wednesday_count;
		week[4].req_count = WeekRequestsCountRow.thursday_count;
		
		$('#who_coming_with_me').children('.list_item').remove();
		renderRows("who_coming_with_me", week, null, { state: 'who_coming_with_me' });		
		refreshThisWeek(SAME_WEEK);
	    minimsg.createTimerMessage("הבקשה אושרה", 3);
	// TODO remove entry from the tab and reduce number of wating requests by one
	});
}

function showRequestTab()
{
	tabs.setSelectedTab(2);
}

function displayWaitingRequestInfo()
{	
	var totalReq = 0;
	if (show_req_info < 4) {
		show_req_info++;
		return "";
	}
	
	for (i=0;i<5;i++)
		totalReq+=week[i].req_count;
	
	if (totalReq == 0)
		var html = " <div style=\"height: 20px\"><\/div> <div class='req_info'> לא נמצאו בקשות חדשות <\/div>";
	else if (totalReq == 1)
		var html = " <div style=\"height: 20px\"><\/div> <div class='req_info'> ממתינה לך בקשה אחת שלא נענתה. <a href=\"javascript:showRequestTab();void 0;\"> לחץ כאן <\/a><\/div>";
	else
		var html = " <div style=\"height: 20px\"><\/div> <div class='req_info'> ממתינות לך " + totalReq + " בקשות שלא נענו.  <a href=\"javascript:showRequestTab();void 0;\"> לחץ כאן <\/a><\/div>";
	
	return html; 
}

function show_req_for_day (data, context) {
	var req_for_day = week[data.dow - 1].req_count;
	
	if (req_for_day == 0)
		return "";
	else if  (req_for_day == 1)
		return "(בקשה אחת טרם נענתה)";
	else
		return "(" + req_for_day + " בקשות טרם נענו)";
}
function DenyRequest(ride_id, passenger_id, email, date, time, from_this_week_tab) {
    var denyVerb = from_this_week_tab ? 'ביטל/ה' : 'דחת/ה';
    var denySubjectVerb = from_this_week_tab ? 'בוטלה' : 'נדחתה';
    var denyNasu = passenger_id == currentUser.user_id ? 'בקשת/ה' : 'בקשתך';
    
    mailText = MAIL_HEADER + currentUser.first_name + ' ' + denyVerb + ' את ' + denyNasu + ' לטרמפ בתאריך ' + date + ' בשעה ' + time + '.<br>' + MAIL_FOOTER;	           				
    
	//alert("ride id = " + ride_id + " passanger_id = " + passenger_id);
	newRequests = [{
					op: 'DB',
					sp: 'sp_DenyRequest',
					params: { db_ride_id: ride_id, db_passenger_id: passenger_id }
					},
					{
				        op: 'SENDMAIL', 
					    to: email,
					    subject: 'בקשת טרמפ ' + denySubjectVerb,
					    message: mailText
					},
					{
					op: 'DB',
					sp: 'sp_GetRequests',
					params: { db_uid: MY_RIDE.uid }
					},
					{
					op: 'DB',
					sp: 'sp_GetCountOfWaitingRequests',
					params: { db_uid: MY_RIDE.uid, db_week_num: currentWeekNum}
					}];
					
	callServer(newRequests, function(response) {
		if (!allResponsesSuccessful(response.data)) return;
		
		if (from_this_week_tab) 			
			minimsg.createTimerMessage("הנסיעה בוטלה", 3);
		else
			minimsg.createTimerMessage("הבקשה נדחתה", 3);
		
		WeekRequestsCountRow = response.data[3].rows[0];
		week[0].req_count = WeekRequestsCountRow.sunday_count;
		week[1].req_count = WeekRequestsCountRow.monday_count;
		week[2].req_count = WeekRequestsCountRow.tuesday_count;
		week[3].req_count = WeekRequestsCountRow.wednesday_count;
		week[4].req_count = WeekRequestsCountRow.thursday_count;
		
		RequestsRows = response.data[2].rows;
		$('#who_coming_with_me').children('.list_item').remove();
		renderRows("who_coming_with_me", week, null, { state: 'who_coming_with_me' });		
		refreshThisWeek(SAME_WEEK);
	// TODO remove entry from the tab and reduce number of wating requests by one
	});
}

function displayTotalRides(data, context) {
	if (data.thisWeek_entries_count > 0)
		return "(" + data.thisWeek_entries_count + ")";
	else
		return "" 
 };

</script>

<link type="text/css" rel="stylesheet" href="http://myridetau.googlecode.com/svn/trunk/css/jquery.autocomplete.css">

<style type="text/css">
	div { direction: rtl; font-family: arial; }
	table { direction: rtl; font-family: arial; }
	input, select { font-size: 11px }			
	.list_item { background: transparent; padding: 5px 5px 5px 0px; }
	.details { padding: 3px 5px 0 0; display: none; width: 98% }		
	.plus { float: right; display: inline; width: 12px; height: 12px; background: url('http://myridetau.googlecode.com/svn/trunk/images/plus.gif') no-repeat; margin: 2px 0px 0px 5px }	
	.minus { background: url('http://myridetau.googlecode.com/svn/trunk/images/minus.gif') no-repeat !important; }
	.template { display: none }
	.map { display: none; height: 350px; }
	.day_part { background-color: #eeeeee; margin: 3px 0px 0px 0px; padding: 3px 3px 3px 0px }	
	.hidden { display: none }
	.ac_loading { background : url('http://myridetau.googlecode.com/svn/trunk/images/loading_small.gif') left center no-repeat; }
	.message_line { position: fixed; bottom: 0px; width: 100% }
	.mmlib_table { width: 100%; font: bold 11px arial,sans-serif; background-color: #fff4c2; border-collapse: separate; border-spacing: 0px; padding: 1px 0px; }
	.loading_big { background : url('http://myridetau.googlecode.com/svn/trunk/images/loading-big.gif') center center no-repeat; }

	#who_take_me .list_item.sel { background: #FFF6D6 !important}
	#this_week  .list_item .details .list_item.sel { background: #FFF6D6 !important}
	#who_coming_with_me .list_item .details .list_item.sel { background: #FFF6D6 !important}		
</style>

<style type="text/css">
    body { font-size: 12px; }
    table tr td { font-size: 12px; }
	label { width: 10em; float: left; }
	label.error { float: none; color: red; padding-right: .5em; vertical-align: top; }
	p { clear: both; }
	.submit { margin-left: 12em; }
	em { font-weight: bold; padding-right: 1em; vertical-align: top; }
</style>

<script type="text/javascript">
  $(document).ready(function(){
	  $("div").addClass("hidden");	
	  
	  $("#userDetailsForm").validate({
			 submitHandler: function(form) {
				saveUserDetails();
			 }
	  });		

	  $("#scheduleForm").validate({
			 submitHandler: function(form) {
				saveUserSchedule();
			 }
		});
  });
</script>


<div id="send_request" class="template">
	<div style="padding-top: 5px">
		הירשם לנסיעה עם {:first_name}<br>
		<textarea id='{:car_owner_id}' rows="1" cols="1" style="width: 250px; height: 70px"></textarea><br>
		<input type="button" value="שלח" onClick="generateRequest('{:car_owner_id}', '{:destid}', '{:dow}', '{:email}', '{:time}', '{:row_idx}');" style="font-size: 11px">
	</div>
</div>

<div id="show_request" class="template">
	<div style="padding-top: 5px">		
		<textarea id='{:car_owner_id}' rows="1" cols="1" style="width: 250px; height: 70px"> {:text_msg} </textarea><br>
		
		<input type="button" value="אשר" onClick="ApproveRequest('{:ride_id}', '{:passenger_id}', '{:email}', '{:date}', '{:time}');" style="font-size: 11px">
		<input type="button" value="דחה" onClick="DenyRequest('{:ride_id}', '{:passenger_id}', '{:email}', '{:date}', '{:time}', false);" style="font-size: 11px">
	</div>
</div>

<div id="show_cancel_button" class="template">
	<div style="padding-top: 5px">		
		<input type="button" value="בטל נסיעה" onClick="DenyRequest('{:ride_id}', '{:passenger_id}', '{:email}', '{:date_part}', '{:time}', true);" style="font-size: 11px">				
	</div>
</div>

<div id="ride_msg" class="template">
<div style="padding-top: 5px">הודעה מ{:first_name}: {:text}</div>
</div>

<div id="show_current_week" class="template">
	<div class="this_week_item">
		<div class="current_week">
			<table width="100%" border="0" cellspacing="0" cellpadding="2">
				<tr>
					<td> <input type="button" value="<< הקודם" onClick='refreshThisWeek(PREV_WEEK);' style="font-size: 11px; width: 75%"></td>
					<td align="center"> שבוע של {:sunday}-{:thursday}
					<td align="left"><input type="button" value="הבא >>" onClick='refreshThisWeek(NEXT_WEEK);' style="font-size: 11px; width: 75%"></td>
				</tr>
			</table>					
		</div>	
	</div>	
</div>

<div id="show_mydate" class="template">
,{:mydate} 
</div>

<div id="user_list_item" class="template">
	<div class="list_item" id='item_{:state}_{:user_id}_{:row_idx}'>
		<a href="javascript:void(0)" class="plus"></a>{:first_name}, {:street}, {:city}, {$who_coming_with_me#show_mydate}{:time}, {:destination}			
		<div class="details">
			<div>				
				<table border="0" cellspacing="0" cellpadding="2" width="100%">				
				<tr>
				    <td width="51" valign="top" rowspan="5"><img srcNoCache="{:image_url}" alt="תמונה" style="float: right; margin-left: 10px; width: 50px "></td>
					<td valign="top" style="width: 70px">שם :</td>
					<td>{:first_name} {:last_name}</td>
				</tr>
				<tr>
					<td valign="top" >מיקום:</td>
					<td>
						רח' {:street} {:house_num}, {:city}
						(<a href='javascript:void(0);' onClick="showMap('map_of_{:state}_{:user_id}_{:row_idx}', '{:lag}', '{:lat}');" 
						    style="font-size: 11px">מפה</a>)
					</td>
				</tr>
				<tr>
					<td valign="top" >פקולטה:</td>
					<td>{:faculty}</td>
				</tr>
				<tr>
					<td valign="top" >תחביבים:</td>
					<td>{:hobbies}</td>
				</tr>
				<tr>
					<td valign="top" >השתתפות:</td>
					<td>{:participation}</td>
				</tr>				
				</table>
				{$this_week#ride_msg}
			</div>
			<div class='map' id='map_of_{:state}_{:user_id}_{:row_idx}'></div>
						
			{$who_take_me#send_request}
			{$who_coming_with_me#show_request}
			{$this_week#show_cancel_button}
		</div>
	</div>
</div>

<div id="minimsg_div" class="message_line">
</div>
 
<div id="this_week">
	<div class="template">
		<div class="this_week_item">	
			<div class="current_week">
				{@renderCurrentWeek}
			</div>
		</div>
		<div class="list_item" style="background: transparent"><a href="javascript:void(0)" class="plus"></a>  יום {:name} {@displayTotalRides}
			<div class="details">
				{@renderThisWeekDay}				
			</div>  
		</div>
		<div class="req_info_item">	
			<div class="req_info">
				{@displayWaitingRequestInfo}
			</div>
		</div>				
	</div>
</div>


<div id="who_take_me">	
	<div id="search_bar" style="padding: 3px 3px 3px 0px">
        <table border="0" cellspacing="0" cellpadding="2"> 
            <tr>
                <td style="width: 90px">חפש טרמפ ליום: </td>
                <td style="padding-left: 5px">
                    <select id="selDay" style="width: 100px" class="day-select">
                        
                    </select>
                </td>				
                <td><input type="button" value="חיפוש" onClick='searchRides();' style="font-size: 11px"></td>
            </tr>
		</table>
	</div>
	<div class="template">
		{$user_list_item}
	</div>	
	<!-- end template -->
</div>

<div id="who_coming_with_me">
	<div class="template">
		<div class="list_item" style="background: white"><a href="javascript:void(0)" class="plus"></a>יום {:name} {@show_req_for_day} 
			<div class="details">
				{@renderWhosCommingWithMe}													
			</div>  
		</div>	
	</div>
</div>


<div id="settings">    
    <div id="new_user_msg" style="text-color: #aaaaaa; text-align: center; padding: 8px 0px 8px 0px; margin: 5px 0px 5px 0px; border: solid 1px #aaaaaa">ברוך הבא ל myRide! כדי להשתמש ב myRide יש למלא מס' פרטים אישיים ולאחר מכן את לוח הזמנים שלך.</div>    
    <div class="list_item">
        <a href="javascript:void(0)" class="plus" id="personal_details"></a>פרטים אישיים
        <div class="details">
            <form id="userDetailsForm" action="/">             
            <table border="0" cellspacing="0" cellpadding="2" width="80%">
                <tr>
                    <td NOWRAP style="width: 100px">שם פרטי</td>
                    <td NOWRAP>
                        <input type="text" id="txtFirstName" class="required" size="25">
                    </td>
                </tr>
                <tr>
                    <td>שם משפחה</td>
                    <td>
                        <input type="text" id="txtLastName" class="required" size="25">
                    </td>
                </tr>
                <tr>
                    <td>אימייל</td>
                    <td>
                        <input type="text" id="txtEmail" class="required" size="25">
                    </td>
                </tr>
                <tr>
                    <td>עיר</td>
                    <td>
                        <input type="text" id="txtCity" class="required" size="25">
                    </td>
                </tr>
                <tr>
                    <td>רחוב</td>
                    <td>
                        <input type="text" id="txtStreet" class="required" size="25">
                    </td>
                </tr>                
                <tr>
                    <td>מספר בית</td>
                    <td>
                        <input type="text" id="txtHouseNum" class="required" size="25">
                    </td>
                </tr>
                <tr>
                    <td>פקולטה</td>
                    <td>
                        <input type="text" id="txtFaculty" size="25">
                    </td>
                </tr>
                  <tr>
                    <td>קישור לתמונה</td>
                    <td>
                        <input type="text" id="txtImageUrl" size="25">
                    </td>
                </tr>
                <tr>
                    <td>תחביבים</td>
                    <td>
                        <input type="text" id="txtHobbies" size="25">
                    </td>
                </tr>
                <tr>
                    <td>השתתפות</td>
                    <td>
                        <input type="text" id="txtParticipation" size="25">
                    </td>
                </tr>
            </table>
            <div style="padding-top: 5px">
                <input type="submit" value="שמור" style="font-size: 11px">
            </div>
            </form>
        </div>
    </div>
    <div class="list_item">
        <a href="javascript:void(0)" class="plus" id="schedule_details"></a>לוח זמנים       	
        <div class="details">
        	<form id="scheduleForm" action="void">
            <table border="0" cellspacing="0" cellpadding="2" width="80%">
                <tr>
                    <td NOWRAP style="width: 70px">יום א' לאוני'</td>
                    <td style="width: 100px">
                        <select id="selSched1-0" class="role-select">
                            
                        </select>
                    </td>
                    <td NOWRAP>יציאה בשעה&nbsp;&nbsp;<input type="text" id="txtSched1-0" size="3"></td>
                </tr>
                <tr>
                    <td>יום א' מהאוני'</td>
                    <td>
                        <select id="selSched1-1" class="role-select">
                            
                        </select>
                    </td>
                    <td>יציאה בשעה&nbsp;&nbsp;<input type="text" id="txtSched1-1" size="3"></td>
                </tr>
                <tr>
                    <td>יום ב' לאוני'</td>
                    <td>
                        <select id="selSched2-0" class="role-select">
                          
                        </select>
                    </td>
                    <td>יציאה בשעה&nbsp;&nbsp;<input type="text" id="txtSched2-0" size="3"></td>
                </tr>
                <tr>
                    <td>יום ב' מהאוני'</td>
                    <td>
                        <select id="selSched2-1" class="role-select">
                            
                        </select>
                    </td>
                    <td>יציאה בשעה&nbsp;&nbsp;<input type="text" id="txtSched2-1" size="3"></td>
                </tr>
                <tr>
                    <td>יום ג' לאוני'</td>
                    <td>
                        <select id="selSched3-0" class="role-select">
                            
                        </select>
                    </td>
                    <td>יציאה בשעה&nbsp;&nbsp;<input type="text" id="txtSched3-0" size="3"></td>
                </tr>
                <tr>
                    <td>יום ג' מהאוני'</td>
                    <td>
                        <select id="selSched3-1" class="role-select">
                            
                        </select>
                    </td>
                    <td>יציאה בשעה&nbsp;&nbsp;<input type="text" id="txtSched3-1" size="3"></td>
                </tr>
                <tr>
                    <td>יום ד' לאוני'</td>
                    <td>
                        <select id="selSched4-0" class="role-select">
                           
                        </select>
                    </td>
                    <td>יציאה בשעה&nbsp;&nbsp;<input type="text" id="txtSched4-0" size="3"></td>
                </tr>
                <tr>
                    <td>יום ד' מהאוני'</td>
                    <td>
                        <select id="selSched4-1" class="role-select">
                            
                        </select>
                    </td>
                    <td>יציאה בשעה&nbsp;&nbsp;<input type="text" id="txtSched4-1" size="3"></td>
                </tr>
                <tr>
                    <td>יום ה' לאוני'</td>
                    <td>
                        <select id="selSched5-0" class="role-select">
                            
                        </select>
                    </td>
                    <td>יציאה בשעה&nbsp;&nbsp;<input type="text" id="txtSched5-0" size="3"></td>
                </tr>
                <tr>
                    <td>יום ה' מהאוני'</td>
                    <td>
                        <select id="selSched5-1" class="role-select">
                            
                        </select>
                    </td>
                    <td>יציאה בשעה&nbsp;&nbsp;<input type="text" id="txtSched5-1" size="3"></td>
                </tr>
            </table>            
            <div style="padding-top: 5px">
                <input type="button" value="שמור" onClick='saveUserSchedule();' style="font-size: 11px">
            </div>
            </form>
        </div>
    </div>
</div>
